package com.woniuxy.moneyapp.app.consumer;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniuxy.commons.config.AlipayConfig;
import com.woniuxy.commons.exception.MyException;
import com.woniuxy.commons.util.Result;
import com.woniuxy.moneyapp.app.controller.form.RechargeStateInfo;
import com.woniuxy.moneyapp.common.enums.PaymentRelated;
import com.woniuxy.moneyapp.common.enums.SchemaCode;
import com.woniuxy.moneyapp.common.exception.code.FundExceptionCode;
import com.woniuxy.moneyapp.common.utils.CommonUtil;
import com.woniuxy.moneyapp.infra.model.CashRecord;
import com.woniuxy.moneyapp.infra.model.PayRecord;
import com.woniuxy.moneyapp.infra.model.RechargeRecord;
import com.woniuxy.moneyapp.service.CashRecordService;
import com.woniuxy.moneyapp.service.PayRecordService;
import com.woniuxy.moneyapp.service.RechargeRecordService;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.SneakyThrows;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Component
@RocketMQMessageListener(topic = "post_recharge_related_info",consumerGroup = "fund_group_recharge")
public class RechargeCheckComsumer implements RocketMQListener<RechargeStateInfo> {

    @Resource
    private PayRecordService payRecordService;

    @Resource
    private RechargeRecordService rechargeRecordService;

    @Resource
    private CashRecordService cashRecordService;

    @Resource
    private StringRedisTemplate srt;


    @SneakyThrows
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void onMessage(RechargeStateInfo orderInfo) {
        System.out.println("充值监听+++++++++++++++++++");
        String s = srt.opsForValue().get("recharge:save:info:"+orderInfo.getOut_trade_no());
        if(s!=null){
            System.out.println("进入防止重复消费+++++++++++++++++++");
            return;
        }
            //1.事务 2.同步锁（更改时 相关的三条信息状态必须一致）
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCashAmount(orderInfo.getCashAmount());
            rechargeRecord.setRechargeNum(orderInfo.getOut_trade_no());
            rechargeRecord.setPayment(PaymentRelated.ALIPAY_NAME.getDesc());
            rechargeRecord.setUserId(orderInfo.getPayerId());
            rechargeRecord.setState(1);
            rechargeRecord.setScence(SchemaCode.RECHARGE_CODE.getNum());
            boolean a = rechargeRecordService.save(rechargeRecord);
            if(!a)
                throw new MyException(FundExceptionCode.DAO_ERROR.getCode(),FundExceptionCode.DAO_ERROR.getMsg());
            //交易流水号的状态只是描述性字段 不用更新 responseTime delete
            PayRecord payRecord = new PayRecord();
            payRecord.setScenceId(rechargeRecord.getId());
            payRecord.setState(1);
            System.out.println("=====================================================");
            System.out.println(orderInfo.getSericalNum());
            boolean b = payRecordService.update(payRecord,new UpdateWrapper<PayRecord>().eq("pay_num",orderInfo.getSericalNum()));
            if(!b) throw new MyException(FundExceptionCode.DAO_ERROR.getCode(),FundExceptionCode.DAO_ERROR.getMsg());
            CashRecord cashRecord = new CashRecord();
            cashRecord.setPayerId(orderInfo.getPayerId());
            cashRecord.setPayerName(orderInfo.getPayerName());
            cashRecord.setCashAmount(orderInfo.getCashAmount());
            cashRecord.setScence(orderInfo.getScence());
            cashRecord.setScenceId(rechargeRecord.getId());
            cashRecord.setPayment(orderInfo.getPayment());
            boolean c = cashRecordService.save(cashRecord);
            if(!c)
                throw new MyException(FundExceptionCode.DAO_ERROR.getCode(),FundExceptionCode.DAO_ERROR.getMsg());
            srt.opsForValue().set("recharge:save:info"+orderInfo.getOut_trade_no(),"order_complete");

    }
    private boolean queryOrder(String orderId) throws AlipayApiException {
        //获取请求
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //用的阿里的 自定义对象 可以理解为js对象
        JSONObject bizContent = new JSONObject();
        //设置参数
        bizContent.put("out_trade_no",orderId);
        //将参数设置到 request请求中
        alipayRequest.setBizContent(bizContent.toString());

        //传入自定义alipayConfig参数
        AlipayClient alipayClient =
                new DefaultAlipayClient(
                        AlipayConfig.gatewayUrl,
                        AlipayConfig.app_id,
                        AlipayConfig.merchant_private_key,
                        "json",
                        AlipayConfig.charset,
                        AlipayConfig.alipay_public_key,
                        AlipayConfig.sign_type);
        AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
        if(response.getTradeStatus().equals("TRADE_SUCCESS")){
            return true;
        }
        return false;

    }

}
